<template>
	<view>
		<canvas canvas-id="waterMark" class="waterMark" :style="{width:windowWidth+'px',height:windowHeight+'px'}"></canvas>
		<image :src="waterMarkUrl" class="waterMark-bg" :style="{width:windowWidth+'px',height:windowHeight+'px'}"></image>
	</view>
</template>

<script>
	export default {
		name: "mz-water-mark",
		props: {
			waterMarkName: {
				type: String,
				default: () => {
					return '我是水印'
				}
			}
		},
		data() {
			return {
				waterMarkUrl: "",
				windowWidth: 100,
				windowHeight: 100,

			};
		},
		mounted() {
			this.drawWaterMark(this.waterMarkName);
		},
		methods: {
			drawWaterMark(text) {
				this.getDeviceInfo().then(response => {
					const w = response.windowWidth;
					const h = response.windowHeight;
					this.windowWidth = w;
					this.windowHeight = h;
					//创建canvas绘制上下文
					const canvas = uni.createCanvasContext("waterMark", this);
					canvas.clearRect(0, 0, w, h)
					//开始创建一个路径，需要调用fill或者stroke才会使用路径进行填充或描边。
					canvas.beginPath();
					canvas.setFontSize(18);
					canvas.setFillStyle('rgba(0, 0, 0, 0.1)');
					canvas.rotate(-30 * Math.PI / 180)
					if (text) {
						text = this.trim(text)
					}
					const maxWidth = text.length * 18
					for (let x = 0; x < 10; x++) {
						for (let y = 0; y < 20; y++) {
							//在画布上绘制被填充的文本。
							canvas.fillText(text, (maxWidth + 40) * x - 400, 90 * y + 20);
						}
					}
					//将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中。
					canvas.draw(false, () => {
						//把当前画布指定区域的内容导出生成指定大小的图片
						uni.canvasToTempFilePath({
							canvasId: "waterMark",
							complete: (res) => {
								this.waterMarkUrl = res.tempFilePath
							}
						}, this)
					})
				});
			},
			trim(str) {
				let trimStr = '';
				const reg = /[\t\r\f\n\s]*/g;
				if (typeof str === 'string') {
					trimStr = str.replace(reg, '');
				}
				return trimStr
			},
			/**
			 * 获取当前设备的信息
			 * **/
			getDeviceInfo() {
				return new Promise((resolve, reject) => {
					uni.getSystemInfo({
						success: (sysInfo) => {
							resolve(sysInfo)
						}
					})
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.waterMark {
		width: 100vw;
		height: 100vh;
		position: fixed;
		transform: translate(-100%, -100%);
		pointer-events: none;
		opacity: 0;

	}

	.waterMark-bg {
		width: 100vw;
		height: 100vh;
		position: fixed;
		top: 0px;
		left: 0px;
		right: 0px;
		bottom: 0px;
		pointer-events: none;
	}
</style>
